const Router = require("koa-router");
const bcrypt = require('bcryptjs');
const gravator = require('gravatar');
const jwt = require('jsonwebtoken');
const passport = require('koa-passport');

const keys = require("../../config/keys");
const router = new Router();



// 引入User
const User = require("../../models/user")

// test
router.get("/test",async ctx => {
    ctx.status = 200;
    ctx.body = {msg:'users works...'};
})


router.post("/register",async ctx =>{
    const findResult = await User.find({email:ctx.request.body.email});
    if (findResult.length > 0){
        ctx.body = {email:'邮箱已经被占用'}
    } else{
        const newUser = new User ({
            name:ctx.request.body.name,
            email:ctx.request.body.email,
            password: ctx.request.body.password,
        });
        await new Promise((resolve)=>{
            bcrypt.genSalt(10,(err,salt) => {
                bcrypt.hash(newUser.password,salt,(err,hash) =>{
                    // console.log('加密密码',hash);
                    try{
                        if(err) throw err;
                    }catch(e){
                        console.log(e.name + ": " + e.message);
                    }

                    newUser.password = hash;
                    resolve();
                })
            })
        })


        // 存储到数据库
        await newUser.save().then(user =>{
            console.log('标记',user)
            ctx.body = user;
        }).catch(err =>{
            console.log(err);
        });
        console.log('注册路由执行')
        ctx.session.user = newUser;
        ctx.body = {success:true,data:newUser};
    }

})

router.post("/login",async ctx =>{
    const findResult = await User.find({email:ctx.request.body.email})
    const user = findResult[0];
    const password = ctx.request.body.password;
    if(findResult.length === 0) {
        ctx.status = 404;
        ctx.body = {email: '用户不存在'};
    } else{
        const result = bcrypt.compareSync(password,user.password)
        if(result){
            ctx.session.user = user;
            ctx.body = {success:true,data:user};
        }else {
            ctx.body = {password:'密码错误'};
        }
    }
})

router.post("/_register",async ctx => {
    console.log(ctx.request.body);
    // 存储到数据库
    const findResult = await User.find({email:ctx.request.body.email});
    // console.log(findResult);
    if(findResult.length > 0){
        ctx.status = 500;
        ctx.body = {email:'邮箱已被占用'};
    }else{
        const avator = gravator.url(ctx.request.body.email,{
            s:'200',
            r:'pg',
            d:'mm'
        })
        const newUser = new User ({
            name:ctx.request.body.name,
            email:ctx.request.body.email,
            password: ctx.request.body.password,
            avator,
        });

        await new Promise((resolve)=>{
            bcrypt.genSalt(10,(err,salt) => {
                bcrypt.hash(newUser.password,salt,(err,hash) =>{
                    // console.log('加密密码',hash);
                    if(err) throw err;
                    newUser.password = hash;
                    resolve();
                })
            })
        })


        // 存储到数据库
        await newUser.save().then(user =>{
            console.log('标记',user)
            ctx.body = user;
        }).catch(err =>{
            console.log(err);
        });

        ctx.body = newUser;

    }
})


router.post('/_login', async ctx =>{
    const findResult = await User.find({ email : ctx.request.body.email });
    const user = findResult[0];
    const password = ctx.request.body.password;
    if(findResult.length === 0) {
        ctx.status = 404;
        ctx.body = {email: '用户不存在'};
    } else{
            const result = bcrypt.compareSync(password,user.password)
            if(result){
                const payload = {id:user.id,name:user.name,avator:user.avator};
                const token = jwt.sign(payload,keys.secretOrKey,{expiresIn:3600});
                ctx.status = 200;
                ctx.body = {success:true,token:"Bearer " + token};
            }else {
                ctx.status = 400;
                ctx.body = {password:'密码错误'};
            }
    }
})

router.get("/current",passport.authenticate('jwt',{session:false}), async ctx => {
    ctx.body = {success:true};
})
module.exports = router.routes();